package com.jack.cms.core.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;

import com.jack.cms.oss.core.UUIDUtil;

/**
 * 
* @ClassName: LoggerMDCFilter 
* @Description: 日志过滤器，埋点处理
* @author Jack-Yuan 
* @date 2017年7月4日 下午5:35:55 
*
 */
public class LoggerMDCFilter implements Filter {
	public static final String HEADER_KEY_KRY_GLOBAL_MSG_ID = "_kry_global_msg_id";
	public static final String IDENTIFIER = "IDENTIFIER";
	public static final String URI_KEY = "URI";

	private String getId(String s) {
		return String.format("%s@", s);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String kryGlobalMsgId = req.getHeader(HEADER_KEY_KRY_GLOBAL_MSG_ID);
		if (StringUtils.isBlank(kryGlobalMsgId)) {
			kryGlobalMsgId = getId(UUIDUtil.getUUID());
		} else {
			kryGlobalMsgId = getId(String.valueOf(kryGlobalMsgId));
		}
		// 唯一标识埋点，设置线程唯一标识，方便查找日志，组合方式 时间戳@请求埋点@线程号
		MDC.put(IDENTIFIER, kryGlobalMsgId);
		// uri_key
		MDC.put(URI_KEY, req.getRequestURI());
		chain.doFilter(request, response);
	}

	/**
	 * 销毁MDC
	 */
	@Override
	public void destroy() {
		MDC.remove(IDENTIFIER);
		MDC.remove(URI_KEY);
	}

}
